package logic

import (
	"context"

	"mall/common/modelx"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/types/setting"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

type SettingListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSettingListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SettingListLogic {
	return &SettingListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SettingListLogic) SettingList(in *setting.SettingListRequest) (*setting.SettingListResponse, error) {
	if in.Preload == "" && in.EagerLoad == "" {
		return nil, status.Error(500, "setting type is missing")
	}

	logx.Infof("SettingListRequest: %+v ", in)

	var settings []*setting.SettingDetailResponse

	preloadMap, _ := modelx.GetPreloadMap(in.Preload, in.EagerLoad)
	blogGeneralSettingName := model.RpcEntityNames.BlogGeneralSetting
	entitySettings, hasEntitySettings := model.RpcEntityPreloadMap[blogGeneralSettingName] // blogGeneralSetting的setting_name集合（及关联字段）
	if hasEntitySettings {
		var settingNames []interface{}
		if preloadFields, hasPreloadFields := preloadMap[blogGeneralSettingName]; hasPreloadFields {
			for _, field := range preloadFields {
				fieldSetting, hasFieldSetting := entitySettings[field]
				if hasFieldSetting && fieldSetting.Name != "" {
					settingNames = append(settingNames, fieldSetting.Name)
				}
			}
		}
		if len(settingNames) > 0 {
			filter := make(map[string]map[string][]interface{})
			filter[model.SettingColumns.SettingName] = map[string][]interface{}{"in": settingNames}
			filter[model.SettingColumns.Autoload] = map[string][]interface{}{"equalTo": []interface{}{true}}
			settingList, _, err := l.svcCtx.Setting.GetList(l.ctx, model.M{}, -1, filter)
			if err != nil {
				return nil, err
			}

			settings = make([]*setting.SettingDetailResponse, 0, len(settingList))
			for _, item := range settingList {
				var autoload int32
				if item.Autoload {
					autoload = 1
				}
				settings = append(settings, &setting.SettingDetailResponse{
					Id:       int64(item.SettingID),
					Name:     item.SettingName,
					Value:    item.SettingValue,
					Autoload: autoload,
				})
			}
		}
	}

	return &setting.SettingListResponse{
		Data: settings,
	}, nil
}
